import { useLocalStorageState } from 'ahooks';
import { STORE_KEYS } from '@/configs/store.config';
import { Game } from '@/types/game';
import { useCallback } from 'react';

export function useHistoryGamesStore() {
  const [historyGames, setHistoryGames] = useLocalStorageState<Game[]>(
    STORE_KEYS.HISTORY_GAMES_STORE,
    {
      defaultValue: [],
    },
  );

  // 因编辑历史比赛数据而暂入缓存的当前对局数据
  const [currentTemGame, setCurrentTemGame] = useLocalStorageState<
    Game | undefined
  >(STORE_KEYS.CURRENT_TEM_GAME, { defaultValue: undefined });

  const unshiftGame = useCallback(
    (game: Game) => {
      // 首先应当先判断是新增还是编辑
      const historyIndex = historyGames.findIndex(
        historyGame => historyGame.startTime === game.startTime,
      );
      if (historyIndex === -1) {
        // 新增则直接加入
        setHistoryGames([game, ...historyGames]);
      } else {
        historyGames.splice(historyIndex, 1, game);
        setHistoryGames([...historyGames]);
      }
    },
    [historyGames, setHistoryGames],
  );

  /** 获取所有对局数据 */
  const getAllHistoryGames = useCallback(() => {
    return historyGames;
  }, [historyGames]);

  function removeHistoryGame(game: Game) {
    setHistoryGames(historyGames.filter(historyGame => historyGame !== game));
  }

  return {
    unshiftGame,
    getAllHistoryGames,
    setCurrentTemGame,
    currentTemGame,
    removeHistoryGame,
  };
}
